package br.com.widgets.listview;

import java.util.List;

import br.com.widgets.models.Paises;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

public class MyAdapter extends ArrayAdapter<Paises> {
	
	private final List<Paises> lista;	
	private final Activity contexto;	
	/**
	 * Construct the class
	 * @param contexto
	 * @param lista
	 */
	public MyAdapter(Activity contexto, List<Paises> lista){
		super(contexto, R.layout.list_row_select, lista);
		this.contexto = contexto;
		this.lista = lista;	
	}
	
	static class ViewHolder{
		protected TextView texto;
		protected CheckBox check;
	}
	
	@Override
	public View getView(int posicao, View convertView, ViewGroup parent){
			View view = null;
			
			if(convertView == null){
				LayoutInflater inflator = contexto.getLayoutInflater();
				view = inflator.inflate(R.layout.list_row_select, null);
				final ViewHolder viewHolder = new ViewHolder();
				viewHolder.texto = (TextView) view.findViewById(R.id.label);
				viewHolder.check = (CheckBox) view.findViewById(R.id.check);
				//Listener	
				viewHolder.check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {					
					public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
						Paises item = (Paises) viewHolder.check.getTag();
						item.setEstaSeleciona(buttonView.isChecked());						
					}					
				});
				view.setTag(viewHolder);
				viewHolder.check.setTag(lista.get(posicao));		
			}else{
				view = convertView;
				((ViewHolder) view.getTag()).check.setTag(lista.get(posicao));
			}
			
			ViewHolder holder = (ViewHolder) view.getTag();
			holder.texto.setText(lista.get(posicao).getNomePais());
			holder.check.setChecked(lista.get(posicao).getEstaSelecionado());
		
			return view;			
	}

}
